package com.modificial.shiro.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.modificial.shiro.system.dao.PermissionDao;
import com.modificial.shiro.system.dao.UserDao;
import com.modificial.shiro.system.dao.UserRoleDao;
import com.modificial.shiro.system.domain.SysRole;
import com.modificial.shiro.system.domain.SysUser;
import com.modificial.shiro.system.domain.SysUserRole;
import com.modificial.shiro.system.exception.ServiceException;
import com.modificial.shiro.system.service.UserService;
import com.modificial.shiro.util.Page;
import com.modificial.shiro.util.SnowFlakeGenerator;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author modificial
 * @date 2018/8/5 0005
 * @company modificial_org
 * @description 用户业务处理
 */
@Service
@Transactional(isolation = Isolation.READ_COMMITTED, rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private PermissionDao permissionDao;

    @Autowired
    private UserRoleDao userRoleDao;

    @Override
    public SysUser findUserByName(String name) {
        Assert.isTrue(StringUtils.hasText(name), "用户名不能为空");
        SysUser sysUser = userDao.findUserByName(name);
        return sysUser;
    }

    @Override
    public int addUser(SysUser sysUser) {
        Assert.notNull(sysUser, "用户信息不能为空");
        Assert.isTrue(StringUtils.hasText(sysUser.getUserName()), "用户名不能为空");
        String name = sysUser.getUserName();
        SysUser user = userDao.findUserByName(name);
        if (user!= null) {
            throw new ServiceException("该用户名已经被占用:" + name);
        }
        String salt=UUID.randomUUID().toString().replaceAll("-","");
        String password=new Md5Hash(sysUser.getPassword(),salt,2).toString();
        sysUser.setSalt(salt);
        sysUser.setPassword(password);
        sysUser.setIsEnable(1);
        sysUser.setCreateTime(new Date());
        sysUser.setUpdateTime(new Date());
        sysUser.setUserId(SnowFlakeGenerator.nextId());
        return userDao.insert(sysUser);
    }

    @Override
    public int updateUser(SysUser sysUser) {
        Assert.notNull(sysUser, "更新用户不能为空");
        SysUser user=userDao.selectByPrimaryKey(sysUser.getUserId());
        if(user!=null) {
            String password = new Md5Hash(sysUser.getPassword(), user.getSalt(),2).toString();
            sysUser.setPassword(password);
        }
        return userDao.updateUser(sysUser);
    }

    @Override
    public int disableUser(String userId, Integer isEnable) {
        Assert.isTrue(StringUtils.hasText(userId) && isEnable != null, "用户id不能为空");
        SysUser sysUser = userDao.selectByPrimaryKey(userId);
        int status = sysUser.getIsEnable();
        if ((status == isEnable)) {
            throw new ServiceException("该用户已被禁用或启用");
        }

        return userDao.disableUser(userId, isEnable);
    }

    @Override
    public Page<SysUser> listUser(Integer nowPage, Integer pageSize) {
        PageHelper.startPage(nowPage, pageSize);
        List<SysUser> sysUserList = userDao.selectAll();
        PageInfo<SysUser> pageInfo = new PageInfo<>(sysUserList);
        Page<SysUser> page = new Page<>(pageInfo.getTotal(), pageInfo.getList(), nowPage, pageSize, pageInfo.getPages());
        return page;
    }

    /**
     * 查询用户角色
     *
     * @param userId
     * @return
     */
    @Override
    public List<SysRole> findRolesByUser(String userId) {
        Assert.isTrue(StringUtils.hasText(userId), "用户id不能为空");
        return userDao.findRolesByUser(userId);
    }

    /**
     * 查询用户权限信息
     * @param userId 用户id
     * @return
     */
    @Override
    public Set<String> findPermissionsByUser(String userId) {
        List<SysRole> roles = findRolesByUser(userId);
        Set<String> permissions = new LinkedHashSet<>();
        roles.forEach(it -> {
            permissions.addAll(permissionDao.findPermissionsByRole(it.getRoleId()));
        });
        return permissions;
    }

    /**
     * 为用户授权
     * @param userId 用户id
     * @param roleId 角色id
     * @return
     */
    @Override
    public int grantRoleForUser(String userId, String roleId) {
        Assert.isTrue(StringUtils.hasText(userId)&&StringUtils.hasText(roleId),
                "用户id或角色id不能为空");
        SysUserRole sysUserRole=new SysUserRole();
        sysUserRole.setRoleId(roleId);
        sysUserRole.setUserId(userId);
        return userRoleDao.insert(sysUserRole);
    }

    /**
     * 根据用户id查询用户
     * @param userId 用户id
     * @return
     */
    @Override
    public SysUser findUserById(String userId) {
        Assert.isTrue(StringUtils.hasText(userId),"用户名不能为空");
       SysUser sysUser=userDao.selectByPrimaryKey(userId);
        return sysUser;
    }

    /**
     * 根据用户id删除用户
     * @param userId 用户id
     * @return
     */
    @Override
    public int deleteUser(String userId) {
        Assert.isTrue(StringUtils.hasText(userId),"用户id不能为空");
        userDao.deleteByPrimaryKey(userId);
        userRoleDao.deleteUser(userId);
        return 1;
    }
}
